layui.define(['form', 'laydate', 'table'], function (exports) {
    var form = layui.form;
    var laydate = layui.laydate;
    var table = layui.table;
    var customerInfoTable = null;
    var view = {
        init: function () {
            this.initTable();
            this.initSearchForm();
            this.initToolBar();
            window.dataReload = function () {
                Lib.doSearchForm($("#searchForm"), customerInfoTable)
            }
        },
        initTable: function () {
            customerInfoTable = table.render({
                elem: '#customerInfoTable',
                height: Lib.getTableHeight(0),
                cellMinWidth: 100,
                method: 'post',
                url: Common.ctxPath + '/customer/customerInfo/list.json' // 数据接口
                , page: Lib.tablePage // 开启分页
                , limit: 10,
                cols: [[ // 表头
                    {
                        type: 'checkbox',
                        fixed: 'left',
                    },
                    {

                        field: 'wxUname',
                        title: '微信昵称',
                    },
                    {

                        field: 'wxPicurl',
                        title: '微信头像',
                        templet:function (d) {
                            if(d.wxPicurl!=""&&d.wxPicurl!=null){
                                return '<div><img src="'+d.wxPicurl+'" class="laytable-cell-1-wxPicurl"></div>'
                            }
                            return "";
                        }
                    },
                    {
                        field: 'customerName',
                        title: '真实姓名',
                    },
                    {

                        field: 'rolesName',
                        title: '会员权限',
                    },
                    {

                        field: 'isTeacher',
                        title: '是否为老师',
                        templet: '<div>{{d.isTeacher==0?"否":"是"}}</div>'
                    },
                    {

                        field: 'phone',
                        title: '绑定手机号',
                    },
                    {

                        field: 'regTypeText',
                        title: '注册类型 ',
                    },
                    {

                        field: 'channelName',
                        title: '来源渠道',
                    },

                    {

                        field: 'custStatus',
                        title: '是否可用',
                        templet: '<div>{{d.custStatus==0?"禁用":"可用"}}</div>'
                    },
                    {

                        field: 'registerTime',
                        title: '注册时间',
                        width : 170,
                    }
                ]]

            });
            table.on('sort(customerInfoTable)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                console.log(obj.field); //当前排序的字段名
                console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
                console.log(this); //当前排序的 th 对象

                //尽管我们的 table 自带排序功能，但并没有请求服务端。
                //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
                table.reload('customerInfoTable', {
                    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
                    , where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                        field: obj.field //排序字段
                        , order: obj.type //排序方式
                    }
                });
            });
            table.on('checkbox(customerInfoTable)', function (obj) {
                var customerInfo = obj.data;
                if (obj.checked) {
                    //按钮逻辑Lib.buttonEnable()
                } else {

                }
            })
        },

        initSearchForm: function () {
            Lib.initSearchForm($("#searchForm"), customerInfoTable, form);
        },
        initToolBar: function () {
            toolbar = {
                add: function () { // 获取选中数据
                    var url = "/customer/customerInfo/add.do";
                    Common.openDlg(url, "会员管理>新增");
                },
                view: function () { // 获取选中数目
                    var data = Common.getOneFromTable(table, "customerInfoTable");
                    if (data == null) {
                        return;
                    }
                    var url = "/customer/customerInfo/view.do?customerId=" + data.customerId+"&tenantId="+data.tenantId;
                    Common.openDlg(url, "会员管理>" + data.customerName + ">查看");
                },
                edit: function () { // 获取选中数目
                    var data = Common.getOneFromTable(table, "customerInfoTable");
                    if (data == null) {
                        return;
                    }
                    var url = "/customer/customerInfo/edit.do?customerId=" + data.customerId+"&tenantId="+data.tenantId;
                    Common.openDlg(url, "会员管理>" + data.wxUname + ">编辑");
                },
                emp: function () { // 获取选中数目
                    var data = Common.getOneFromTable(table, "customerInfoTable");
                    if (data == null) {
                        return;
                    }
                    var url = "/customer/customerInfo/emp.do?customerId=" + data.customerId+"&tenantId="+data.tenantId;
                    Common.openDlg(url, "会员管理>" + data.wxUname + ">编辑");
                },
                teacher: function () { // 获取选中数目
                    var data = Common.getMoreDataFromTable(table, "customerInfoTable");
                    if (data == null) {
                        return;
                    }
                    if(data.customerName==""||data.customerName==null){
                        Common.info("真实姓名不能为空");
                        return;
                    }
                    Common.openConfirm("确认要把这些会员设为老师？", function () {
                        var ids = Common.concatBatchId(data, "customerId");
                        Common.post("/customer/customerInfo/teacher.json", {"ids": ids}, function () {
                            Common.info("设置成功");
                            dataReload();
                        })
                    })
                },
                del: function () {
                    layui.use(['del'], function () {
                        var delView = layui.del;
                        delView.delBatch();
                    });
                },
                grant: function () { // 授权为咨询师
                    var data = Common.getOneFromTable(table, "customerInfoTable");
                    if (data == null) {
                        return;
                    }
                    var url = "/customer/customerInfo/grant.do?customerId="+data.customerId;
                    var title = "老师授权管理>"+data.customerName;
                    Common.openDlg(url,title);
                },
                grantCustomer: function () { // 授权为咨询师
                    var data = Common.getOneFromTable(table, "customerInfoTable");
                    if (data == null) {
                        return;
                    }
                    var url = "/customer/customerInfo/grantCustomer.do?customerId="+data.customerId;
                    var title = "会员授权管理>"+data.customerName;
                    Common.openDlg(url,title);
                },
                exam: function () { // 获取选中数目
                    var data = Common.getOneFromTable(table, "customerInfoTable");
                    if (data == null) {
                        return;
                    }
                    var url = "/customer/customerInfo/exam.do?customerId="+ data.customerId;
                    Common.openDlg(url, "高考信息修改管理>" + data.customerName );
                },
                login:function () {
                    // var data = Common.getOneFromTable(table,"customerInfoTable");
                    // if(data==null){
                    //     return ;
                    // }
                    // var origin = window.location.origin
                    // var customerId = data.customerId
                    // var url="";
                    // if(origin.indexOf("qitian.51sdx.com")>=0){
                    //     url = "http://m.51sdx.com/p/qtwlh5s?customerId="+customerId;
                    // }else if(origin.indexOf("cms.51sdx.com")>=0){
                    //     if(data.channel == "GSW001"){
                    //         url = "http://m.51sdx.com/p/gswh5?customerId="+customerId;
                    //     }else{
                    //         url = "http://m.51sdx.com/p/choice?customerId="+customerId;
                    //     }
                    // }else{
                    //     url = "http://m.51sdx.com/t/choice?customerId="+customerId;
                    // }
                    // // window.open(url);
                    // CopyToClipboard(url);
                    var data = Common.getOneFromTable(table,"customerInfoTable");
                    if(data==null){
                        return ;
                    }
                    $.ajax({
                        type: 'POST',
                        url: Common.ctxPath+"/customer/customerInfo/login.json",
                        data: {
                            customerId:data.customerId
                        },
                        dataType:'json',
                        success: function(res){
                           console.log(res);
                           if(res.code==0){
                               var url = res.data.loginPath+"/autoLogin?customerToken="+res.data.customerToken;
                               window.open(url);
                           }
                        }
                    });

                },
                h5login:function () {
                    var data = Common.getOneFromTable(table,"customerInfoTable");
                    if(data==null){
                        return ;
                    }
                    $.ajax({
                        type: 'POST',
                        url: Common.ctxPath+"/customer/customerInfo/login.json",
                        data: {
                            customerId:data.customerId,
                            type:2
                        },
                        dataType:'json',
                        success: function(res){
                            if(res.code==0){
                                var url = res.data.loginPath+"/est/autoLogin?customerToken="+res.data.customerToken;
                                window.open(url);
                            }
                        }
                    });

                },
                importDocument:function(){
                    var uploadUrl = Common.ctxPath+"/customer/customerInfo/excel/import.do";
                    //模板,
                    var templatePath= "/customer/customerInfo_upload_template.xls";
                    //公共的简单上传文件处理
                    var url = "/core/file/simpleUpload.do?uploadUrl="+uploadUrl+"&templatePath="+templatePath;
                    Common.openDlg(url, "CustomerInfo管理>上传");
                },
                revokeRead: function () { // 收回热点精读权限
                    var data = Common.getMoreDataFromTable(table, "customerInfoTable");
                    if (data == null) {
                        return;
                    }
                    Common.openConfirm("确认要收回热点精读权限？", function () {
                        var ids = Common.concatBatchId(data, "customerId");
                        Common.post("/customer/customerInfo/revokeRead.json", {"ids": ids}, function () {
                            Common.info("操作成功");
                            dataReload();
                        })
                    })
                },

                };
                $('.ext-toolbar').on('click', function () {
                    var type = $(this).data('type');
                    toolbar[type] ? toolbar[type].call(this) : '';
                });
        }
    }

    function CopyToClipboard (input) {
        var textToClipboard = input;

        var success = true;
        if (window.clipboardData) { // Internet Explorer
            window.clipboardData.setData ("Text", textToClipboard);
        }
        else {
            // create a temporary element for the execCommand method
            var forExecElement = CreateElementForExecCommand (textToClipboard);

            /* Select the contents of the element
                (the execCommand for 'copy' method works on the selection) */
            SelectContent (forExecElement);

            var supported = true;

            // UniversalXPConnect privilege is required for clipboard access in Firefox
            try {
                if (window.netscape && netscape.security) {
                    netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect");
                }

                // Copy the selected content to the clipboard
                // Works in Firefox and in Safari before version 5
                success = document.execCommand ("copy", false, null);
            }
            catch (e) {
                success = false;
            }

            // remove the temporary element
            document.body.removeChild (forExecElement);
        }

        if (success) {
            Common.info("复制成功");
        }
        else {
            Common.info ("您的浏览器不允许剪贴板访问！");
        }
    }

    function CreateElementForExecCommand (textToClipboard) {
        var forExecElement = document.createElement ("div");
        // place outside the visible area
        forExecElement.style.position = "absolute";
        forExecElement.style.left = "-10000px";
        forExecElement.style.top = "-10000px";
        // write the necessary text into the element and append to the document
        forExecElement.textContent = textToClipboard;
        document.body.appendChild (forExecElement);
        // the contentEditable mode is necessary for the  execCommand method in Firefox
        forExecElement.contentEditable = true;

        return forExecElement;
    }

    function SelectContent (element) {
        // first create a range
        var rangeToSelect = document.createRange();
        rangeToSelect.selectNodeContents(element);

        // select the contents
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(rangeToSelect);
    }
    exports('index', view);

});
